// LoginWidget.cpp
#include "LoginWidget.h"
#include <QFormLayout>
#include <QGroupBox>
#include <QHBoxLayout>

#include "ElaLineEdit.h"

#include <QDebug>

LoginWidget::LoginWidget(QWidget *parent) : QWidget(parent) {
    initUI();
    initConnections();
}

void LoginWidget::initUI() {
    // 标题
    m_titleText = new ElaText(tr("登录"), this);
    m_titleText->setTextStyle(ElaTextType::Title);

    // 输入控件
    m_usernameEdit = new ElaLineEdit(this);
    m_usernameEdit->setPlaceholderText(tr("请输入用户名"));
    m_passwordEdit = new ElaLineEdit(this);
    m_passwordEdit->setPlaceholderText(tr("请输入密码"));
    m_rememberCheck = new ElaCheckBox(tr("记住密码"), this);

    // 按钮
    m_loginBtn = new ElaPushButton(tr("登录"), this);
    m_signInBtn = new ElaPushButton(tr("注册"), this);

    // 布局
    ElaText *le_userName = new ElaText(tr("用户名:"), this);
    le_userName->setTextStyle(ElaTextType::Body);
    ElaText *le_userPwd = new ElaText(tr("密码:"), this);
    le_userPwd->setTextStyle(ElaTextType::Body);

    QFormLayout *formLayout = new QFormLayout();
    formLayout->addRow(le_userName, m_usernameEdit);
    formLayout->addRow(le_userPwd, m_passwordEdit);
    formLayout->addRow(nullptr, m_rememberCheck);

    QGroupBox *formGroup = new QGroupBox(this);
    formGroup->setLayout(formLayout);

    QHBoxLayout *btnLayout = new QHBoxLayout();
    btnLayout->addWidget(m_loginBtn);
    btnLayout->addWidget(m_signInBtn);

    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(m_titleText, 0, Qt::AlignCenter);
    mainLayout->addWidget(formGroup);
    mainLayout->addLayout(btnLayout);
}

void LoginWidget::initConnections() {
    // 注册按钮点击切换界面
    connect(m_signInBtn, &ElaPushButton::clicked, this, &LoginWidget::switchToSignIn);

    // 登录按钮点击校验输入
    connect(m_loginBtn, &ElaPushButton::clicked, [this](){
        const QString username = m_usernameEdit->text().trimmed();
        const QString password = m_passwordEdit->text().trimmed();

        if(username.isEmpty() || password.isEmpty()) {
            qDebug() << "用户名或密码不能为空";
            return;
        }
        qDebug() << "发送信息";
        emit loginRequested(username, password);
    });
}
